﻿using System;
using System.Collections.Generic;
using UnityEditor.MemoryProfiler;
using UnityEngine;

namespace PerfAssist.MemoryProfilerAdvanced.Editor.PAContrib
{
    public class MemCompareTarget
    {
        public static MemCompareTarget Instance = new MemCompareTarget();

        [SerializeField] private PackedCrawlerData _packedCrawled;

        [NonSerialized] private PackedMemorySnapshot _snapshot;

        [NonSerialized] private CrawledMemorySnapshot _unpackedCrawl;

        public CrawledMemorySnapshot UnpackedTargetSnapshot
        {
            get { return _unpackedCrawl; }
        }

        public void SetCompareTarget(PackedMemorySnapshot snapshot)
        {
            _snapshot = snapshot;
            _packedCrawled = new Crawler().Crawl(_snapshot);
            _unpackedCrawl = CrawlDataUnpacker.Unpack(_packedCrawled);
        }

        public HashSet<int> GetNewlyAdded(CrawledMemorySnapshot latestCrawl)
        {
            var compTargets = new HashSet<int>();
            foreach (var item in _unpackedCrawl.allObjects)
            {
                var n = item as NativeUnityEngineObject;
                if (n != null) compTargets.Add(n.instanceID);
            }

            var newlyAdded = new HashSet<int>();
            foreach (var item in latestCrawl.allObjects)
            {
                var n = item as NativeUnityEngineObject;
                if (n != null && !compTargets.Contains(n.instanceID)) newlyAdded.Add(n.instanceID);
            }

            return newlyAdded;
        }
    }
}